#include <config.h>
#include <board.h>
#include <init.h>
#include <os.h>
#include <bitmap.h>
#include <bitops.h>
#include <settings.h>
#include "ES8P508x.h"
#include "lib_config.h"
#include "device.h"
#include "printk.h"
#include "es8p508_adc.h"

#ifdef configUSING_ADC
static struct device adc_dev;

uint16_t ad_temp;
size_t adc_read(device_t *dev, off_t pos, void *buffer, size_t size)
{
		uint8_t i;
		uint16_t max, min, sum, ad_temp;

		max = 0x00;
		min = 0x0fff;
		sum = 0x00;

		for (i=0; i<18; i++)
		{
			ADC_Start();
			while(ADC_GetFlagStatus(ADC_IF) == RESET);
			ad_temp = ADC_GetConvValue();
			ADC_ClearIFStatus(ADC_IF);

			if (ad_temp > max)
			{
					max = ad_temp;
			}
			if (ad_temp < min)
			{
					min = ad_temp;
			}
			sum += ad_temp;
		}
		sum -= min;
		sum -= max;
		return (sum >> 4);
}


static void adc_gpio_init(void)
{
	GPIO_InitStruType x;
	ADC_InitStruType y;

	x.GPIO_Signal		= GPIO_Pin_Signal_Analog;
	x.GPIO_Func			= GPIO_Func_0;
	x.GPIO_Direction= GPIO_Dir_In;
	x.GPIO_PUEN			= GPIO_PUE_Input_Disable;
	x.GPIO_PDEN			= GPIO_PDE_Input_Disable;
	x.GPIO_OD			  = GPIO_ODE_Output_Disable;
	x.GPIO_DS			  = GPIO_DS_Output_Normal;
	GPIO_Init(PIR_PORT, PIR_PIN, &x); 

	y.ADC_ChS 			= ADC_CHS_AIN0;  	//AIN6
	y.ADC_ClkS 			= ADC_ClkS_PCLK;	//PCLK
	y.ADC_ClkDiv 		= ADC_ClkDiv_32;
	y.ADC_VrefP 		= ADC_VrefP_Vcc;
	y.ADC_SampS 		= ADC_SMPS_HARD;
	y.ST 				    = 7;
	y.ADC_VREFN 		= ENABLE;
	y.ADC_VRBUF_EN 	= ENABLE;
	ADC_Init(&y);
	ADC_IE_Disable();
	ADC_Enable();
}

static struct device_ops adc_ops =
{
    .read = adc_read,
};

int board_setup_adc(void)
{
	  adc_gpio_init();

    adc_dev.ops = &adc_ops;
    device_register(&adc_dev, "pir", 0);

    return 0;
}

device_initcall(board_setup_adc);
#endif
